﻿using System;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using Consul;
using Newtonsoft.Json;

namespace ConsumerOneService
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var consulClient = new ConsulClient(x =>
            {
                x.Address = new Uri("http://127.0.0.1:8500");
            }))
            {
                var consulServices = consulClient.Agent.Services().Result.Response;

                //foreach (var item in consulServices.Values)
                //{
                //    Console.WriteLine($"ID:{item.ID},Service:{item.Service},Address:{item.Address},Port:{item.Port}");
                //}

                var msgServices = consulServices.Values.Where(x => x.Service.Equals("MsgService", StringComparison.OrdinalIgnoreCase));

                while (true)
                {

                    var randomMsgServiceIndex = DateTime.Now.Second % msgServices.Count();

                    var randomMsgService = msgServices.ElementAt(randomMsgServiceIndex);

                    Console.WriteLine($"Index:{randomMsgServiceIndex},ID:{randomMsgService.ID},Service:{randomMsgService.Service},Address:{randomMsgService.Address},Port:{randomMsgService.Port}");

                    using (var httpClient = new HttpClient())
                    {
                        var requestAnonymous = new
                        {
                            PhoneNum = "13153181639",
                            Msg = "HELP!!!!!!!!!!!!!!!!!!!!!!!!"
                        };
                        using (var requstContext = new StringContent(JsonConvert.SerializeObject(requestAnonymous), Encoding.UTF8, "application/json"))
                        {
                            var responseCode = httpClient.PostAsync($"http://{randomMsgService.Address}:{randomMsgService.Port}/api/SMS/Send_LX", requstContext).Result;

                            Console.WriteLine($"ResponseCode:{responseCode.StatusCode}");
                        }
                    }

                    Thread.Sleep(500);
                }
            }

            Console.ReadKey();
        }
    }
}
